<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of SoftwareController
 *
 * @author thanhdx
 */
class SoftwareController extends Controller {

    //public $layout = 'column2';
    private $__model;

    public function actionCreate() {
        $model = $this->loadModel();
        $this->performAjaxValidation($model); //validate via ajax
        if ($_POST['Software']) {
            $model->attributes = $_POST['Software'];
            if ($model->validate() && $model->save()) {
                //$this->redirect('');
            }
        }
        $this->render("create", array('model' => $model));
    }

    public function actionUpdate($id) {

        $model = $this->loadModel($id);
        $this->performAjaxValidation($model); //validate via ajax
        if ($_POST['Software']) {
            $model->attributes = $_POST['Software'];
            if (!$model->getIsNewRecord() && $model->update()) {
                $this->redirect('../../');
            }
        }
        $this->render("edit", array('model' => $model));
    }

    public function actionIndex() {
        $model = new Software('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Software']))
            $model->attributes = $_GET['Software'];

        $this->render('list', array(
            'model' => $model,
        ));
    }

    private function loadModel($id=null) {
        if ($this->__model === null) {
            if ($id != null) {
                if (Yii::app()->user->isGuest)
                    $condition = 'status=' . Software::STATUS_PUBLISHED;
                else
                    $condition='';
                $this->__model = Software::model()->findByPk($id, $condition);
            }else {
                $this->__model = new Software;
            }
            if ($this->__model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $this->__model;
    }

    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'software-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}

?>
